package com.application.admin;

import com.application.model.Area;
import com.jfinal.ext.tree.TreeUtil;
import com.jfinal.ext.tree.ZtreeNode;
import com.jfinal.kit.StrKit;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 地区管理
 */
@Controller("/admin/area")
public class AreaController extends BaseController {

    public void index() {

        paging(splitPage, "com.application.area.splitPageSelect", "com.application.area.splitPageFrom");

        renderOk(splitPage);
    }

/*
{
    "msg": "",
    "data": [
        {
            "成都": [
                {
                    "value": 2,
                    "key": "武侯区"
                },
                {
                    "value": 3,
                    "key": "成华区"
                }
            ]
        }
    ],
    "url": "",
    "status": 200
}
 */
    public void selectData(){
        List<Area> areas = Area.dao.find("select * from t_area order by level, ord");
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<Area> cityList = areas.stream().filter(area -> area.getInt("level") == 1).collect(Collectors.toList());

        for (Area city : cityList) {
            Map<String, Object> subMap = new HashMap<>();
            List<Map<String, String>> subList = new ArrayList<>();
            subMap.put("city", city.get("name"));
            subMap.put("list", subList);
            mapList.add(subMap);
            for (Area area : areas) {
                if (area.getInt("parent_id") == city.getInt("id")) {
                    Map<String, String> map = new HashMap<>();
                    map.put("name", area.get("name"));
                    map.put("id", area.get("id"));
                    subList.add(map);
                }
            }
        }

        renderOk(mapList);
    }

    public void treeData() {
        List<Area> areas = Area.dao.find("select * from t_area order by ord");

        Area root = new Area();
        root.set("id", 0);
        root.set("name", "地区列表");
        root.set("status", 1).set("ord", 0);
        root.set("parent_id", null);
        areas.add(root);

        List<ZtreeNode> nodeList = new ArrayList<>();
        ZtreeNode node = null;

        for (Area area : areas) {
            String pid = area.get("parent_id") == null ? null : area.get("parent_id").toString();
            node = new ZtreeNode();
            node.setId(area.getPKValue());
            node.setName(area.getStr("name"));
            node.setParentId(pid);
            node.setIcon("");
            node.setOrd(area.getInt("ord"));
            node.setOperator(area.getInt("status") == 0 ? "已停用" : "已启用");
            nodeList.add(node);
        }

        TreeUtil.setRootCode("");
        List<ZtreeNode> ztreeNodes = TreeUtil.getJsonList(nodeList);

        renderOk("", "成功", ztreeNodes);
    }

    /*
    @param {parentids}
     */
    public void save() {
        Area obj = Area.dao.create(super.getParamMap());
        if(obj.save()){
            renderOk("reload", "添加成功", null);
        } else {
            renderErr(400, "", "保存失败");
        }
    }


    public void updateOptional() {

        String did = getPara() == null ? ids : getPara();
        String orderids = getPara("ord");
        String name = getPara("name");
        String pid = getPara("parent_id");
        Area area = new Area();
        area.set("id", did);

        if (!StrKit.isBlank(orderids)) {
            area.set("ord", Integer.parseInt(orderids));
        }

        if (!StrKit.isBlank(name)) {
            area.set("name", name);
        }

        if (!StrKit.isBlank(pid)) {
            Area pd = Area.dao.findById(pid);
            area.set("level", pd.getInt("level") + 1);
            area.set("parent_id", pid);
            area.set("path",  pd.get("path") + "/" + pid);
        }

        if(area.update()){
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(400, "", "修改失败");
        }

    }

    /*
    同步修改path
     */
    public void update() {
        String id = getPara() == null ? getPara("id") : getPara();
        String pid = getPara("parent_id");
        Area obj = new Area();
        int level = 1;
        if(StrKit.notBlank(pid) && !"0".equalsIgnoreCase(pid)){
            Area pd = Area.dao.findById(pid);
            level = pd.getInt("level") + 1;
            obj.set("parent_id", pid);
            obj.set("path", pd.get("path") + "/" + pd.getId());
        } else {
            obj.set("path", 0);
        }

        obj.set("level", level);
        obj.set("name", getPara("name"));
        obj.set("ord", getParaToInt("ord"));
        obj.set("status", getPara("status"));
        obj.set("id", id);
        obj.set("parent_id", pid);

        obj.update();

        renderOk("refresh", "修改成功", null);
    }

    /**
     * 删除
     */
    public void delete() {
        Area.dao.deleteByIds(getPara() == null ? getPara("checkbox") : getPara());
        renderOk("refresh", "删除成功", null);
    }


    public void view(){
        Area area = Area.dao.findDetail(getPara());
        renderOk(area);
    }

    /**
     * @param level=3,keyword
     */
    public void query(){
        List<Area> list = Area.dao.query(getPara("keyword"));
        renderOk(list);
    }
}
